/*
 *
 */

package com.hlingsoft.kkh.action.v20;


import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import com.hlingsoft.kkh.action.BaseAction;
import com.hlingsoft.kkh.dao.*;
import com.hlingsoft.kkh.entity.*;
import com.hlingsoft.kkh.entity.Event;
import com.hlingsoft.kkh.entity.Image;
import com.hlingsoft.kkh.entity.vo.EventsSearchVo;
import com.hlingsoft.kkh.entity.vo.EventsVo;
import com.hlingsoft.kkh.entity.vo.EventsVo1;
import com.hlingsoft.kkh.entity.vo.ImageVo;
import com.hlingsoft.kkh.util.Common;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * 职位
 *
 * @author Herbert
 */
@Controller
@RequestMapping("/v20/event")

public class EventsAction_V20 extends BaseAction {


    private final int rows=10;




    /**
     * 添加活动现场
     */
    @RequestMapping(value = "/add.json")
    @ResponseBody
    public Map<String, Object> add(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "description") String description,
            @RequestParam(value = "createAddress") String createAddress,
            @RequestParam(value = "interestIds",required = false) String interestIds,
            @RequestParam(value = "interestId",required = false) Integer interestId,
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "tokeTimes",required = false) String tokeTimes,
            @RequestParam("files") MultipartFile[] files,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser appUser = userDao.getUserById(appUserId);
            if (appUser!=null) {

                String msg = name + "活动现场已存在";
                if (eventsDao.getEventsByNameAndAddress(name, createAddress).size() != 0) {
                    resultMap.put("msg", msg);
                } else {
                    Events event = new Events();
                    String images = "";

                    List<ImageVo> imageVoList = new ArrayList<ImageVo>();

                    if (tokeTimes != null) {
                        JSONArray jsonArray = JSONArray.fromObject(tokeTimes);
                        long[] tokeTimeArray = (long[]) JSONArray.toArray(jsonArray, long.class);


                        for (int i = 0; i < tokeTimeArray.length; i++) {
                            ImageVo imageVo = new ImageVo();
                            imageVo.setFile(files[i]);

                            Date date = Common.transferLongToDate(tokeTimeArray[i] / 1000);   //long类型转成Date类型
                            imageVo.setDate(date);
                            imageVoList.add(imageVo);
                        }
                    } else {
                        for (int i = 0; i < files.length; i++) {
                            ImageVo imageVo = new ImageVo();
                            imageVo.setFile(files[i]);
                            imageVo.setDate(new Date());
                            imageVoList.add(imageVo);
                        }
                    }


                    for (ImageVo imageVo : imageVoList) {
                        String fileName = imageVo.getFile().getOriginalFilename();
                        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String dateString = simpleFormat.format(new Date());
                        putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                                imageVo.getFile().getSize());
                        images += "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName + ",";

                    }

                    if (images.length() > 0) {
                        images = images.substring(0, images.length() - 1);
                    }

                    //添加events
                    event.setName(name);
                    event.setImages(images);
                    event.setDescription(description);
                    event.setCreateAddress(createAddress);
                    event.setAppUserId(appUserId);
                    event.setCreateTime(new Date());
                    event.setUpdateTime(new Date());
                    if (interestId!=null){
                        event.setInterestIds(interestId.toString());
                    }else {
                        event.setInterestIds(interestIds);
                    }
                    event.setProfessionId(appUser.getProfessionId());  //根据用户的职业默认发布的社区设定为职业组社区
                    event.setLatitude(latitude);
                    event.setLongitude(longitude);
                    eventsDao.addEvents(event);
                    resultMap.put("eventId", event.getId());//返回添加的eventId
                    resultMap.put("images", images);        //返回添加的images


                    //添加eventsComments
                    EventComments eventComments = new EventComments();
                    eventComments.setContent(description);
                    eventComments.setEventId(event.getId());
                    eventComments.setImage(images);
                    eventComments.setLikeCount(0);
                    eventComments.setUnlikeCount(0);
                    eventComments.setShareCount(0);
                    eventComments.setAppUserId(appUserId);
                    eventComments.setCreateTime(new Date());
                    eventComments.setUpdateTime(new Date());
                    eventComments.setType(1);
                    eventCommentsDao.addEventComments(eventComments);


                    //添加图片
                    for (ImageVo imageVo : imageVoList) {
                        Image image = new Image();

                        //图片地址
                        String fileName = imageVo.getFile().getOriginalFilename();
                        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String dateString = simpleFormat.format(new Date());
                        putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                                imageVo.getFile().getSize());
                        String path = "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName;
                        image.setPath(path);

                        image.setAppUserId(appUserId);
                        image.setEventCommentsId(eventComments.getId());
                        image.setEventsId(event.getId());
                        image.setTagId(0);
                        image.setCreateTime(new Date());
                        image.setUpdateTime(new Date());
                        image.setTokeTime(imageVo.getDate());
                        image.setAvailable(1);
                        imageDao.addImage(image);
                    }
                }
            }else {
                resultMap.put("msg","您的账号有异常，请确认后发帖");
            }
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * android 创建
     * @param name
     * @param description
     * @param createAddress
     * @param appUserId
     * @param latitude
     * @param longitude
     * @param tokeTimes
     * @param file1
     * @param file2
     * @param file3
     * @param file4
     * @param request
     * @return
     */
    @RequestMapping(value = "/addB.json")
    @ResponseBody
    public Map<String, Object> add(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "description") String description,
            @RequestParam(value = "createAddress") String createAddress,
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "interestId",required = false) Integer interestId,
            @RequestParam(value = "interestIds",required = false) String interestIds,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "tokeTimes") String tokeTimes,
            @RequestParam(value = "file1",required = false) MultipartFile file1,
            @RequestParam(value = "file2",required = false) MultipartFile file2,
            @RequestParam(value = "file3",required = false) MultipartFile file3,
            @RequestParam(value = "file4",required = false) MultipartFile file4,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser appUser = userDao.getUserById(appUserId);
            if (appUser!=null) {

                String msg = name + "活动现场已存在";
                if (eventsDao.getEventsByNameAndAddress(name, createAddress).size() != 0) {
                    resultMap.put("msg", msg);
                } else {
                    Events event = new Events();
                    String images = "";

                    JSONArray jsonArray = JSONArray.fromObject(tokeTimes);
                    long[] tokeTimeArray = (long[]) JSONArray.toArray(jsonArray, long.class);
                    List<MultipartFile> filesList = new ArrayList<MultipartFile>();
                    if (file1 != null) {
                        filesList.add(file1);
                    }
                    if (file2 != null) {
                        filesList.add(file2);
                    }
                    if (file3 != null) {
                        filesList.add(file3);
                    }
                    if (file4 != null) {
                        filesList.add(file4);
                    }

                    List<ImageVo> imageVoList = new ArrayList<ImageVo>();
                    for (int i = 0; i < tokeTimeArray.length; i++) {

                        ImageVo imageVo = new ImageVo();
                        imageVo.setFile(filesList.get(i));

                        Date date = Common.transferLongToDate(tokeTimeArray[i] / 1000);   //long类型转成Date类型
                        imageVo.setDate(date);
                        imageVoList.add(imageVo);
                    }

                    for (ImageVo imageVo : imageVoList) {
                        String fileName = imageVo.getFile().getOriginalFilename();
                        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String dateString = simpleFormat.format(new Date());
                        putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                                imageVo.getFile().getSize());
                        images += "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName + ",";

                    }

                    if (images.length() > 0) {
                        images = images.substring(0, images.length() - 1);
                    }

                    //添加events
                    event.setName(name);
                    event.setImages(images);
                    event.setDescription(description);
                    event.setCreateAddress(createAddress);
                    event.setAppUserId(appUserId);
                    event.setProfessionId(appUser.getProfessionId());
                    event.setCreateTime(new Date());
                    event.setUpdateTime(new Date());
                    event.setLatitude(latitude);
                    event.setLongitude(longitude);
                    if (interestId!=null){
                        event.setInterestIds(interestId.toString());
                    }else {
                        event.setInterestIds(interestIds);
                    }
                    eventsDao.addEvents(event);
                    resultMap.put("eventId", event.getId());//返回添加的eventId
                    resultMap.put("images", images);        //返回添加的images


                    //添加eventsComments
                    EventComments eventComments = new EventComments();
                    eventComments.setContent(description);
                    eventComments.setEventId(event.getId());
                    eventComments.setImage(images);
                    eventComments.setLikeCount(0);
                    eventComments.setUnlikeCount(0);
                    eventComments.setShareCount(0);
                    eventComments.setAppUserId(appUserId);
                    eventComments.setCreateTime(new Date());
                    eventComments.setUpdateTime(new Date());


                    eventComments.setType(1);
                    eventCommentsDao.addEventComments(eventComments);


                    //添加图片
                    for (ImageVo imageVo : imageVoList) {
                        Image image = new Image();

                        //图片地址
                        String fileName = imageVo.getFile().getOriginalFilename();
                        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String dateString = simpleFormat.format(new Date());
                        putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                                imageVo.getFile().getSize());
                        String path = "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName;
                        image.setPath(path);

                        image.setAppUserId(appUserId);
                        image.setEventCommentsId(eventComments.getId());
                        image.setEventsId(event.getId());
                        image.setTagId(0);
                        image.setCreateTime(new Date());
                        image.setUpdateTime(new Date());
                        image.setTokeTime(imageVo.getDate());
                        image.setAvailable(1);
                        imageDao.addImage(image);
                    }

                }
            }else {
                resultMap.put("msg","您的账号有异常，请确认后发帖");
            }
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 活动详情
     * @param request
     * @return
     */
    @RequestMapping(value = "/detail.json")
    @ResponseBody
    public Map<String, Object> detail(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "eventId") long eventId,
            @RequestParam(value = "pageNum",defaultValue = "1",required = false) int pageNum,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Events events=eventsDao.getEventsById(eventId);
            if (events!=null){
                List<EventComments> eventCommentsList = eventCommentsDao.getImageCommentsListByEventId(eventId, 2,(pageNum-1)*rows,rows);
                for (EventComments eventComments:eventCommentsList){
                    List<Image> imageList = imageDao.getImageByEventCommentsId(eventComments.getId());
                    List<AppUser> likeUserList = new ArrayList<AppUser>();
                    eventComments.setImageList(imageList);
                    if (likesDao.getCIsLikes(userId, eventComments.getId()).size() != 0) {
                        eventComments.setIslike(1);
                    } else {
                        eventComments.setIslike(0);
                    }
                    List<Likes> likesList = likesDao.getLikesByEventCommentsId(eventComments.getId(), 0, 10);
                    for (Likes likes : likesList) {
                        AppUser user = userDao.getUserById(likes.getMyId());
                        if (user!=null){
                            likeUserList.add(user);
                        }
                    }
                    eventComments.setLikeUserList(likeUserList);
                    eventComments.setLikeCount(likesDao.getLikesByEventCommentsIdCount(eventComments.getId()));
                    List<Reply> replyList= replyDao.getReplyByEventCommentsId(eventComments.getId(), 0, 5);
                    Collections.sort(replyList, new Comparator<Reply>() {
                        @Override
                        public int compare(Reply o1, Reply o2) {
                            return o1.getCreateTime().compareTo(o2.getCreateTime());
                        }
                    });
                    eventComments.setReplyList(replyList);
                    eventComments.setUserName(userDao.getUserById(eventComments.getAppUserId()).getName());
                    eventComments.setHeadImage(userDao.getUserById(eventComments.getAppUserId()).getHeadImage());
                }
                resultMap.put("events",events);
                resultMap.put("eventCommentsList",eventCommentsList);
                resultMap.put("result",true);
            } else {
                resultMap.put("msg","该社区已被删除");
                resultMap.put("result",false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;

    }



    public void putObject(String date, String filename, InputStream content,
                          Long size) throws FileNotFoundException {

        // 初始化OSSClient
        OSSClient client = new OSSClient("W6PVM427mSEWlvEz",
                "h7NoXlxcjCqyeOWeuT43LungGmGRSd");

        // 获取指定文件的输入流
        // File file = new File(filePath);
        // InputStream content = new FileInputStream(file);

        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();

        // 必须设置ContentLength
        meta.setContentLength(size);

        // 上传Object.
        PutObjectResult result = client.putObject("kkh", "upload/" + date
                + "/" + filename, content, meta);


        // 打印ETag
        System.out.println(result.getETag());
    }

}
